import channels.layers
import psutil
from asgiref.sync import async_to_sync
from celery import shared_task

from .models import SystemStatus


@shared_task
def server_monitor():
    mem = psutil.virtual_memory()
    cpu_num = psutil.cpu_count()
    cpu_utilization = psutil.cpu_percent(0.1)
    mem_total = mem.total / (1024 * 1024)
    mem_used = mem.used / (1024 * 1024)

    sys_state = SystemStatus()
    sys_state.cpu_num = cpu_num
    sys_state.cpu_utilization = cpu_utilization
    sys_state.mem_total = mem_total
    sys_state.mem_used = mem_used
    sys_state.save()

    push_data = {
        'cpu_num': cpu_num,
        'cpu_utilization': cpu_utilization,
        'mem_total': mem_total,
        'mem_used': mem_used
    }

    channel_layer = channels.layers.get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        'server_monitor_group',
        {
            'type': 'server.monitor',
            'data': push_data
        }
    )

    # ServerMonitorWebsocket.push_data(push_data)
